package com.yihaodian.index.meta;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.yihaodian.index.meta.shard.Shard;
import com.yihaodian.index.meta.shard.ShardId;
import com.yihaodian.index.meta.shard.impl.ModShardHandler;
import com.yihaodian.index.solr.SolrConfigs;

public class IndexMeta {

	/**
	 * solr config/schema
	 */
	SolrConfigs solrConfigs;

	String indexId;

	/**
	 * number of shards
	 */
	int shardNumber;

	/**
	 * <shardId, Shard>
	 */
	Map<String, Shard> shardMap;

	/**
	 * <shardId, version>
	 */
	Map<String, String> version;

	String shardHandlerClass = ModShardHandler.class.getCanonicalName();

	String shardHandlerParam = null;

	public IndexMeta(String indexId, int shardNumber) {
		this.indexId = indexId;
		this.shardNumber = shardNumber;

		shardMap = new HashMap<String, Shard>();
		version = new HashMap<String, String>();

		for (int i = 0; i < shardNumber; i++) {
			String id = "s" + i;
			Shard shard = new Shard(indexId, id);
			shardMap.put(shard.getShardId().getShardId(), shard);
			version.put(shard.getShardId().getShardId(), "" + 0);
		}
	}

	public SolrConfigs getSolrConfigs() {
		return solrConfigs;
	}

	public void setSolrConfigs(SolrConfigs solrConfigs) {
		this.solrConfigs = solrConfigs;
	}

	public String version(ShardId shardId) {
		return version.get(shardId.getShardId());
	}

	public void setVersion(String shard, String version) {
		this.version.put(shard, version);
	}

	public void setVersion(Map<String, String> version) {
		this.version = version;
	}

	public String getIndexId() {
		return indexId;
	}

	public void setIndexId(String indexId) {
		this.indexId = indexId;
	}

	public Collection<Shard> getShards() {
		return shardMap.values();
	}

	public void setShards(Collection<Shard> shards) {
		if (shards != null) {
			for (Shard shard : shards) {
				shardMap.put(shard.getShardId().getShardId(), shard);
			}
		}
	}

	public Shard getShard(ShardId shardId) {
		return shardMap.get(shardId.getShardId());
	}

	/**
	 * get unique id of the schema, might be index-schema-version
	 * 
	 * @return
	 */
	public String getId() {
		return indexId;
	}

	public String getShardHandlerClass() {
		return shardHandlerClass;
	}

	public void setShardHandler(String shardHandler) {
		this.shardHandlerClass = shardHandler;
	}

	public String getShardHandlerParam() {
		return shardHandlerParam;
	}

	public void setShardHandlerParam(String shardHandlerParam) {
		this.shardHandlerParam = shardHandlerParam;
	}

	/**
	 * TODO builder
	 */
	public IndexMeta clone() {
		IndexMeta mt = new IndexMeta(this.indexId, this.shardNumber);
		mt.solrConfigs = this.solrConfigs;
		mt.shardHandlerClass = this.shardHandlerClass;
		mt.shardHandlerParam = this.shardHandlerParam;
		mt.shardMap = new HashMap<String, Shard>(this.shardMap);
		mt.version = new HashMap<String, String>(this.version);

		return mt;
	}

}
